package org.testing;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class LoginSystem {

	public static User userLogin(String login) throws FileNotFoundException {
		Scanner file_scan = new Scanner(new FileReader("users"));
		while(file_scan.hasNext()){	
			String f_out=file_scan.nextLine();
			String[] buf = f_out.split("/");
			if (buf[1].equals(login)) {
				if (buf[2].equals("admin")) {
					return new User(login, true);
				} else {
					return new User(login, false);
				}
			}	
		}
		return null;
	}

	public static void singUp(String login) throws IOException {
		Integer id = Integer.parseInt(readLastLine("users").split("/")[0])+1;
		FileWriter wr = new FileWriter("users",true);
		wr.write(id.toString());
		wr.write("/");
		wr.write(login);
		wr.write("/");
		wr.write("student");
		wr.write("\r\n");
		wr.close(); 	
	}
	
	public static String readLastLine( String fileName ) {
	    try {
	        java.io.File file = new java.io.File( fileName );
	        java.io.RandomAccessFile fileHandler = new java.io.RandomAccessFile( file, "r" );
	        long fileLength = file.length() - 1;
	        StringBuilder sb = new StringBuilder();
	 
	        for( long filePointer = fileLength; filePointer != -1; filePointer-- ) {
	            fileHandler.seek( filePointer );
	            int readByte = fileHandler.readByte();                
	 
	            if( readByte == 0xA ) {
	                if( filePointer == fileLength ) {
	                    continue;
	                } else {
	                    break;
	                }
	            } else if( readByte == 0xD ) {
	                if( filePointer == fileLength - 1 ) {
	                    continue;
	                } else {
	                    break;
	                }                    
	            }
	 
	            sb.append( ( char ) readByte );
	        }
	 
	        String lastLine = sb.reverse().toString();
	        return lastLine;
	    } catch( java.io.FileNotFoundException e ) {
	        e.printStackTrace();
	        return null;
	    } catch( java.io.IOException e ) {
	        e.printStackTrace();
	        return null;
	    }
	}
}
